import request from "@/utils/request";

/**
 * 注意：这是一个模拟数据API文件，用于演示和测试
 * 实际项目中请使用 @/api/pack/locator.js 中的真实API
 * 当前使用真实API的页面：/views/locator/index.vue
 */

// 生成mock数据的工具函数
function generateMockLocators(pageNum = 1, pageSize = 10) {
  const total = 50;
  const data = [];
  const start = (pageNum - 1) * pageSize;
  const end = Math.min(start + pageSize, total);

  for (let i = start; i < end; i++) {
    const id = i + 1;
    data.push({
      id: id,
      imei: `86013${String(id).padStart(10, "0")}`,
      deviceName: `定位器${String.fromCharCode(65 + (i % 26))}${id}`,
      deviceModel: ["GT06N", "GT02A", "GT300"][i % 3],
      simNumber: `1380013${String(id).padStart(4, "0")}`,
      deviceStatus: String((i % 3) + 1),
      batteryLevel: Math.floor(Math.random() * 100),
      signalStrength: -(Math.floor(Math.random() * 50) + 50),
      lastReportTime: new Date(
        Date.now() - Math.random() * 24 * 60 * 60 * 1000
      ),
      currentLocation: {
        longitude: 116.397428 + (Math.random() - 0.5) * 0.1,
        latitude: 39.90923 + (Math.random() - 0.5) * 0.1,
        address: `北京市朝阳区某某街道${Math.floor(Math.random() * 100)}号`,
        locationTime: new Date(Date.now() - Math.random() * 60 * 60 * 1000),
        accuracy: Math.floor(Math.random() * 50) + 5,
      },
      boundWaybill:
        i % 3 === 0
          ? {
              waybillNo: `WB${String(Date.now() + i).slice(-8)}`,
              senderName: `发货人${i}`,
              receiverName: `收货人${i}`,
              bindTime: new Date(
                Date.now() - Math.random() * 7 * 24 * 60 * 60 * 1000
              ),
              status: String((i % 4) + 1),
            }
          : null,
      createTime: new Date(
        Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000
      ),
      remark: i % 5 === 0 ? `备注信息${i}` : null,
    });
  }

  return {
    code: 200,
    msg: "查询成功",
    rows: data,
    total: total,
  };
}

// 查询定位器列表
export function listLocator(query) {
  return new Promise((resolve) => {
    setTimeout(() => {
      let mockData = generateMockLocators(
        query.pageNum || 1,
        query.pageSize || 10
      );

      // 根据搜索条件过滤数据
      if (query.imei) {
        mockData.rows = mockData.rows.filter((item) =>
          item.imei.toLowerCase().includes(query.imei.toLowerCase())
        );
      }

      if (
        query.bindStatus !== null &&
        query.bindStatus !== undefined &&
        query.bindStatus !== ""
      ) {
        mockData.rows = mockData.rows.filter((item) => {
          const isBound = item.boundWaybill ? "1" : "0";
          return isBound === query.bindStatus;
        });
      }

      if (query.deviceStatus) {
        mockData.rows = mockData.rows.filter(
          (item) => item.deviceStatus === query.deviceStatus
        );
      }

      mockData.total = mockData.rows.length;

      resolve({
        code: 200,
        msg: "查询成功",
        rows: mockData.rows,
        total: mockData.total,
      });
    }, 300);
  });
}

// 查询定位器详细
export function getLocator(locatorId) {
  return new Promise((resolve) => {
    setTimeout(() => {
      const mockData = generateMockLocators(1, 1).rows[0];
      mockData.id = locatorId;
      mockData.imei = `86013${String(locatorId).padStart(10, "0")}`;
      mockData.totalDistance = Math.floor(Math.random() * 10000);
      mockData.totalOnlineTime = Math.floor(Math.random() * 1000);
      mockData.totalReports = Math.floor(Math.random() * 50000);
      mockData.totalAlarms = Math.floor(Math.random() * 100);
      resolve({
        code: 200,
        msg: "查询成功",
        data: mockData,
      });
    }, 200);
  });
}

// 新增定位器
export function addLocator(data) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        code: 200,
        msg: "新增成功",
      });
    }, 500);
  });
}

// 修改定位器
export function updateLocator(data) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        code: 200,
        msg: "修改成功",
      });
    }, 500);
  });
}

// 删除定位器
export function delLocator(locatorId) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        code: 200,
        msg: "删除成功",
      });
    }, 300);
  });
}

// 解绑运单
export function unbindShipment(locatorId) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        code: 200,
        msg: "解绑成功",
      });
    }, 500);
  });
}

// 批量解绑运单
export function batchUnbindShipment(locatorIds) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        code: 200,
        msg: `成功解绑${locatorIds.length}个设备`,
      });
    }, 800);
  });
}

// 更新设备状态
export function updateLocatorStatus(data) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        code: 200,
        msg: "状态更新成功",
      });
    }, 400);
  });
}

// 导出定位器
export function exportLocator(query) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        code: 200,
        msg: "导出成功",
        data: "mock-export-url",
      });
    }, 1000);
  });
}

// 获取定位器导入模板
export function importTemplate() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        code: 200,
        msg: "获取模板成功",
        data: "mock-template-url",
      });
    }, 300);
  });
}

// 定位器数据导入
export function importData(data) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        code: 200,
        msg: "导入成功",
        data: {
          successCount: Math.floor(Math.random() * 50) + 10,
          failCount: Math.floor(Math.random() * 5),
        },
      });
    }, 2000);
  });
}

// 生成位置日志mock数据
function generateMockLocationLogs(deviceImei, pageNum = 1, pageSize = 10) {
  const total = 200;
  const data = [];
  const start = (pageNum - 1) * pageSize;
  const end = Math.min(start + pageSize, total);
  const now = new Date();

  for (let i = start; i < end; i++) {
    const time = new Date(now.getTime() - i * 10 * 60 * 1000); // 每10分钟一条记录
    data.push({
      id: i + 1,
      deviceImei: deviceImei,
      locationTime: time,
      longitude: 116.397428 + (Math.random() - 0.5) * 0.1,
      latitude: 39.90923 + (Math.random() - 0.5) * 0.1,
      address: `北京市朝阳区某某街道${Math.floor(Math.random() * 100)}号`,
      locationType: String(Math.floor(Math.random() * 3) + 1),
      accuracy: Math.floor(Math.random() * 50) + 5,
      speed: Math.floor(Math.random() * 80),
      direction: Math.floor(Math.random() * 360),
      altitude: Math.floor(Math.random() * 100) + 50,
      batteryLevel: Math.floor(Math.random() * 100),
      signalStrength: -(Math.floor(Math.random() * 50) + 50),
      satelliteCount: Math.floor(Math.random() * 12) + 4,
      networkType: ["4G", "3G", "WIFI"][Math.floor(Math.random() * 3)],
    });
  }

  return {
    code: 200,
    msg: "查询成功",
    rows: data,
    total: total,
  };
}

// 查询定位日志列表
export function getLocationLogs(query) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(
        generateMockLocationLogs(
          query.deviceImei,
          query.pageNum,
          query.pageSize
        )
      );
    }, 400);
  });
}

// 查询定位日志详细
export function getLocationLogDetail(logId) {
  return new Promise((resolve) => {
    setTimeout(() => {
      const mockData = generateMockLocationLogs("860130000000001", 1, 1)
        .rows[0];
      mockData.id = logId;
      resolve({
        code: 200,
        msg: "查询成功",
        data: mockData,
      });
    }, 200);
  });
}

// 获取定位器统计信息
export function getLocatorStats() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        code: 200,
        msg: "查询成功",
        data: {
          totalCount: 50,
          boundCount: 25,
          unboundCount: 25,
          lowBatteryCount: 5,
        },
      });
    }, 300);
  });
}

// 获取定位器电量统计
export function getBatteryStats() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        code: 200,
        msg: "查询成功",
        data: {
          high: 30,
          medium: 15,
          low: 5,
          averageLevel: 75,
        },
      });
    }, 200);
  });
}

// 检查IMEI号码唯一性
export function checkImeiUnique(imei, locatorId) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        code: 200,
        msg: "检查完成",
        data: {
          unique: Math.random() > 0.2,
        },
      });
    }, 300);
  });
}

// 获取设备配置
export function getLocatorConfig(locatorId) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        code: 200,
        msg: "查询成功",
        data: {
          locatorId: locatorId,
          reportInterval: 60,
          sleepMode: false,
          gpsMode: 1,
          alarmSettings: {
            lowBattery: true,
            geofence: true,
            vibration: false,
          },
          networkSettings: {
            apn: "cmnet",
            serverHost: "47.100.100.100",
            serverPort: 8080,
          },
        },
      });
    }, 300);
  });
}

// 更新设备配置
export function updateLocatorConfig(data) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        code: 200,
        msg: "配置更新成功",
      });
    }, 500);
  });
}

// 发送设备指令
export function sendCommand(data) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        code: 200,
        msg: "指令发送成功",
        data: {
          commandId: "CMD" + Date.now(),
          status: "sent",
        },
      });
    }, 400);
  });
}

// 获取设备指令历史
export function getCommandHistory(locatorId) {
  return new Promise((resolve) => {
    setTimeout(() => {
      const data = [];
      for (let i = 0; i < 10; i++) {
        data.push({
          id: i + 1,
          commandId: "CMD" + (Date.now() - i * 1000),
          commandType: ["位置查询", "重启设备", "参数设置"][i % 3],
          sendTime: new Date(Date.now() - i * 60 * 60 * 1000),
          status: ["已发送", "已执行", "执行失败"][i % 3],
          result: i % 3 === 2 ? "设备离线" : "执行成功",
        });
      }
      resolve({
        code: 200,
        msg: "查询成功",
        data: data,
      });
    }, 300);
  });
}

// 获取地理围栏列表
export function getGeofences(locatorId) {
  return new Promise((resolve) => {
    setTimeout(() => {
      const data = [];
      for (let i = 0; i < 3; i++) {
        data.push({
          id: i + 1,
          name: `围栏${i + 1}`,
          type: ["circle", "polygon"][i % 2],
          center: {
            longitude: 116.397428 + (Math.random() - 0.5) * 0.01,
            latitude: 39.90923 + (Math.random() - 0.5) * 0.01,
          },
          radius: Math.floor(Math.random() * 1000) + 100,
          alertType: ["进入", "离开", "进入或离开"][i % 3],
          status: String(i % 2),
          createTime: new Date(Date.now() - i * 24 * 60 * 60 * 1000),
        });
      }
      resolve({
        code: 200,
        msg: "查询成功",
        data: data,
      });
    }, 300);
  });
}

// 创建地理围栏
export function createGeofence(data) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        code: 200,
        msg: "围栏创建成功",
      });
    }, 500);
  });
}

// 删除地理围栏
export function deleteGeofence(geofenceId) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        code: 200,
        msg: "围栏删除成功",
      });
    }, 300);
  });
}

// 获取告警记录
export function getAlerts(query) {
  return new Promise((resolve) => {
    setTimeout(() => {
      const data = [];
      const total = 30;
      const pageSize = query.pageSize || 10;
      const pageNum = query.pageNum || 1;
      const start = (pageNum - 1) * pageSize;
      const end = Math.min(start + pageSize, total);

      for (let i = start; i < end; i++) {
        data.push({
          id: i + 1,
          locatorId: Math.floor(Math.random() * 50) + 1,
          imei: `86013${String(i + 1).padStart(10, "0")}`,
          alertType: ["低电量", "围栏告警", "震动告警", "离线告警"][i % 4],
          alertLevel: ["低", "中", "高"][i % 3],
          alertTime: new Date(Date.now() - i * 60 * 60 * 1000),
          status: ["未处理", "已处理"][i % 2],
          description: `告警描述信息${i + 1}`,
          handleTime:
            i % 2 === 1 ? new Date(Date.now() - i * 30 * 60 * 1000) : null,
          handler: i % 2 === 1 ? `处理人${i}` : null,
        });
      }
      resolve({
        code: 200,
        msg: "查询成功",
        rows: data,
        total: total,
      });
    }, 400);
  });
}

// 处理告警
export function handleAlert(alertId, data) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        code: 200,
        msg: "告警处理成功",
      });
    }, 300);
  });
}

// 获取轨迹回放数据
export function getTrackPlayback(query) {
  return new Promise((resolve) => {
    setTimeout(() => {
      const data = [];
      const pointCount = 50;
      const startTime = new Date(query.startTime);
      const endTime = new Date(query.endTime);
      const timeInterval = (endTime - startTime) / pointCount;

      for (let i = 0; i < pointCount; i++) {
        data.push({
          longitude: 116.397428 + (Math.random() - 0.5) * 0.01,
          latitude: 39.90923 + (Math.random() - 0.5) * 0.01,
          time: new Date(startTime.getTime() + i * timeInterval),
          speed: Math.floor(Math.random() * 60),
          direction: Math.floor(Math.random() * 360),
          address: `北京市朝阳区某某街道${Math.floor(Math.random() * 100)}号`,
        });
      }
      resolve({
        code: 200,
        msg: "查询成功",
        data: data,
      });
    }, 600);
  });
}

// 导出轨迹数据
export function exportTrack(query) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        code: 200,
        msg: "轨迹导出成功",
        data: "mock-track-export-url",
      });
    }, 1200);
  });
}

// 获取附近定位器
export function getNearbyLocators(longitude, latitude, radius) {
  return new Promise((resolve) => {
    setTimeout(() => {
      const data = [];
      const count = Math.floor(Math.random() * 10) + 1;
      for (let i = 0; i < count; i++) {
        data.push({
          id: i + 1,
          imei: `86013${String(i + 1).padStart(10, "0")}`,
          deviceName: `附近设备${i + 1}`,
          longitude: longitude + (Math.random() - 0.5) * 0.01,
          latitude: latitude + (Math.random() - 0.5) * 0.01,
          distance: Math.floor(Math.random() * radius),
          lastReportTime: new Date(Date.now() - Math.random() * 60 * 60 * 1000),
        });
      }
      resolve({
        code: 200,
        msg: "查询成功",
        data: data,
      });
    }, 400);
  });
}

// 地理编码（地址转坐标）
export function geocode(address) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        code: 200,
        msg: "地理编码成功",
        data: {
          longitude: 116.397428 + (Math.random() - 0.5) * 0.1,
          latitude: 39.90923 + (Math.random() - 0.5) * 0.1,
          address: address,
          confidence: Math.floor(Math.random() * 30) + 70,
        },
      });
    }, 300);
  });
}

// 逆地理编码（坐标转地址）
export function reverseGeocode(longitude, latitude) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        code: 200,
        msg: "逆地理编码成功",
        data: {
          longitude: longitude,
          latitude: latitude,
          address: `北京市朝阳区某某街道${Math.floor(Math.random() * 100)}号`,
          province: "北京市",
          city: "北京市",
          district: "朝阳区",
        },
      });
    }, 300);
  });
}

// 获取定位器分组列表
export function getLocatorGroups() {
  return new Promise((resolve) => {
    setTimeout(() => {
      const data = [];
      for (let i = 0; i < 5; i++) {
        data.push({
          id: i + 1,
          name: `分组${i + 1}`,
          description: `这是分组${i + 1}的描述`,
          memberCount: Math.floor(Math.random() * 20) + 1,
          createTime: new Date(Date.now() - i * 7 * 24 * 60 * 60 * 1000),
          status: String(i % 2),
        });
      }
      resolve({
        code: 200,
        msg: "查询成功",
        data: data,
      });
    }, 300);
  });
}

// 创建定位器分组
export function createLocatorGroup(data) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        code: 200,
        msg: "分组创建成功",
      });
    }, 500);
  });
}

// 更新定位器分组
export function updateLocatorGroup(data) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        code: 200,
        msg: "分组更新成功",
      });
    }, 500);
  });
}

// 删除定位器分组
export function deleteLocatorGroup(groupId) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        code: 200,
        msg: "分组删除成功",
      });
    }, 300);
  });
}

// 将定位器添加到分组
export function addToGroup(groupId, locatorIds) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        code: 200,
        msg: `成功添加${locatorIds.length}个设备到分组`,
      });
    }, 400);
  });
}

// 从分组中移除定位器
export function removeFromGroup(groupId, locatorIds) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        code: 200,
        msg: `成功从分组中移除${locatorIds.length}个设备`,
      });
    }, 400);
  });
}

// 获取定位器维护记录
export function getMaintenanceRecords(locatorId) {
  return new Promise((resolve) => {
    setTimeout(() => {
      const data = [];
      for (let i = 0; i < 8; i++) {
        data.push({
          id: i + 1,
          locatorId: locatorId,
          maintenanceType: ["日常检查", "故障维修", "电池更换", "固件升级"][
            i % 4
          ],
          description: `维护描述信息${i + 1}`,
          maintenanceTime: new Date(Date.now() - i * 7 * 24 * 60 * 60 * 1000),
          maintainer: `维护人员${i + 1}`,
          cost: Math.floor(Math.random() * 500) + 50,
          status: ["进行中", "已完成", "已取消"][i % 3],
          remark: i % 3 === 0 ? `备注信息${i + 1}` : null,
          createTime: new Date(Date.now() - i * 7 * 24 * 60 * 60 * 1000),
        });
      }
      resolve({
        code: 200,
        msg: "查询成功",
        data: data,
      });
    }, 300);
  });
}

// 创建维护记录
export function createMaintenanceRecord(data) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        code: 200,
        msg: "维护记录创建成功",
      });
    }, 500);
  });
}

// 更新维护记录
export function updateMaintenanceRecord(data) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        code: 200,
        msg: "维护记录更新成功",
      });
    }, 500);
  });
}

// 删除维护记录
export function deleteMaintenanceRecord(recordId) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        code: 200,
        msg: "维护记录删除成功",
      });
    }, 300);
  });
}
